package ioc

import (
	"gitee.com/itgsyang/restful-api-demo/apps/hosts/http"
	"gitee.com/itgsyang/restful-api-demo/apps/hosts/integration/start"
	"gitee.com/itgsyang/restful-api-demo/apps/hosts/repository/dao"
	"gitee.com/itgsyang/restful-api-demo/conf"
	"go.uber.org/zap"
	"log"
	"os"
	"os/signal"
	"syscall"
)

func InitHosts() {

	l, err := zap.NewDevelopment()
	if err != nil {
		panic(err)
	}
	err = conf.LoadConfigFromFile("/etc/demo.toml")
	if err != nil {
		panic(err)
	}
	httpServer := start.NewHttpServer(l)
	db := conf.LoadDB()
	svc := dao.NewHostDao(l, db)
	host := http.NewHostHandler(svc)
	host.Register(httpServer.R)

	svi := NewManager(httpServer)
	ch := make(chan os.Signal, 1)
	defer close(ch)
	signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGHUP)
	go svi.WaitStop(ch)

	err = svi.Start()
	if err != nil {
		l.Info("http服务启动失败", zap.Error(err))
	}
}

func NewManager(server *start.HttpServer) *Manager {
	return &Manager{Server: server}
}

type Manager struct {
	Server *start.HttpServer
}

func (m *Manager) Start() error {
	return m.Server.Start()
}

func (m *Manager) WaitStop(ch <-chan os.Signal) {
	for v := range ch {
		log.Printf("系统信号: %s", v.String())
	}
}
